﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Schedulr.Providers;

namespace Schedulr.Infrastructure
{
    /// <summary>
    /// Provides logging services.
    /// </summary>
    public static class Logger
    {
        #region Static Fields

        /// <summary>
        /// The trace source to log to.
        /// </summary>
        private static TraceSource tracer;

        /// <summary>
        /// The synchronisation object to lock on.
        /// </summary>
        private static object lockObject;

        #endregion

        #region Static Constructor

        /// <summary>
        /// Initializes the <see cref="Logger"/> class.
        /// </summary>
        static Logger()
        {
            lockObject = new object();
            tracer = new TraceSource("Schedulr");
            tracer.Listeners.Add(new TextWriterTraceListener(PathProvider.LogFilePath));
        }

        #endregion

        #region Log

        /// <summary>
        /// Logs an exception.
        /// </summary>
        /// <param name="message">The message to trace.</param>
        /// <param name="exception">The exception that occurred.</param>
        public static void Log(string message, Exception exception)
        {
            string errorMessage = message;
            if (exception != null)
            {
                errorMessage += string.Format(CultureInfo.CurrentCulture, ": {0}", exception.ToString());
            }
            Log(errorMessage, TraceEventType.Error);
        }

        /// <summary>
        /// Logs a message.
        /// </summary>
        /// <param name="message">The message to trace.</param>
        /// <param name="eventType">The type of event that caused the trace.</param>
        public static void Log(string message, TraceEventType eventType)
        {
            lock (lockObject)
            {
                string fullMessage = string.Format(CultureInfo.CurrentCulture, "{0}[T{1:00}] [{2}] {3}", new string(' ', 11 - eventType.ToString().Length), Thread.CurrentThread.ManagedThreadId, DateTime.Now, message);
                tracer.TraceEvent(eventType, 0, fullMessage);
                tracer.Flush();
            }
        }

        #endregion
    }
}